﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ShopayServer.Http
{
    public class Request: IDisposable
    {
        public HttpListenerRequest request;
        public string url;
        public string method;
        public System.Collections.Specialized.NameValueCollection queryData;
        public JToken inputData;


        public Request(HttpListenerRequest request)
        {
            this.request = request;

            // 开始解析
            handle();
        }

        private void handle()
        {
            url = request.Url.LocalPath;
            method = request.HttpMethod.ToUpper();

            // GET 请求
            queryData = request.QueryString;

            // POST 请求
            Stream stream = request.InputStream;
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string content = reader.ReadToEnd();

            try
            {
                // 转化为 JSON
                object obj = JsonConvert.DeserializeObject(content.Length > 0 ? content : "{}");

                // 根据类型来创建对应实例
                inputData = Activator.CreateInstance(obj.GetType(), obj) as JToken;
            }
            catch (Exception e)
            {
                inputData = new JObject();
            }
        }

        public string query(string name)
        {
            return queryData.Get(name);
        }

        public JToken input(string name)
        {
            return inputData[name];
        }

        public void Dispose()
        {
            request = null;
            url = null;
            method = null;
            queryData = null;
            inputData = null;

            GC.SuppressFinalize(this);
        }
    }
}
